<template>
  <div class="comment-section">
    <h3>评论区</h3>
    <!-- 评论列表 -->
    <div class="comment-list-scroll">
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else>
        <div v-if="comments.length === 0" class="no-comment">暂无评论</div>
        <CommentItem v-for="comment in comments.filter(c => c.parentId === 0)" :key="comment.id" :comment="comment" :all-comments="comments" />
      </div>
    </div>

    <!-- 发布评论输入框 -->
    <div class="comment-input-row">
      <img :src="userInfo.avatar" alt="头像" class="comment-avatar" @click="goToCurrentUserProfile" style="cursor: pointer;" />
      <input v-model="content" placeholder="写下你的评论..." class="comment-input" @keyup.enter="submitComment" />
      <button class="primary-btn" @click="submitComment" :disabled="!content.trim() || getUserId() === 4">发布评论</button>
    </div>

    <div v-if="showLoginTip" class="login-tip">请先登录后再评论</div>
  </div>
</template>

<script setup>
import {onMounted, ref, watch} from 'vue';
import axios from 'axios';
import CommentItem from './CommentItem.vue';
import { currentUser } from '../user';
import { useRouter } from 'vue-router';
const router = useRouter();

// 跳转到当前用户主页
function goToCurrentUserProfile() {
  const userId = getUserId();
  if (userId && userId !== 4) {
    router.push(`/user/${userId}`);
  }
}

/**
 * 定义组件接收的 props
 * @property {Number|String} activityId - 动态 ID，用于获取评论和动态内容
 */
const props = defineProps({
  activityId: {type: [Number, String], required: true},
});

// 响应式数据
const comments = ref([]);
const loading = ref(false);
const content = ref('');
const showLoginTip = ref(false);

const userInfo = ref({
  nickname: '匿名用户',
  avatar: 'https://example.com/avatars/guest1.jpg'
});

// 加载当前用户信息
onMounted(() => {
  if (currentUser.id) {
    userInfo.value.nickname = currentUser.nickname || '匿名用户';
    userInfo.value.avatar = currentUser.avatar || 'https://example.com/avatars/guest1.jpg';
  }
});
/**
 * 获取当前用户 ID
 * @returns {Number} 用户 ID，如果未登录则返回默认值 4
 */
const getUserId = () => {
  const userId = localStorage.getItem('userId');
  return userId ? Number(userId) : 4;
};

/**
 * 获取指定动态的评论列表
 * @returns {Promise<void>}
 */
async function fetchComments() {
  loading.value = true;
  try {
    const response = await axios.get(`http://localhost:8085/comments/activity/${props.activityId}`);
    comments.value = response.data;
  } catch (e) {
    comments.value = [];
  }
  loading.value = false;
}

/**
 * 提交新评论
 * @returns {Promise<void>}
 */
async function submitComment() {
  if (getUserId() === 4) {
    showLoginTip.value = true;
    return;
  }
  if (!content.value.trim()) return;
  const newComment = {
    activityId: props.activityId,
    userId: getUserId(),
    parentId: 0,
    content: content.value,
    createDate: new Date(),
    updateDate: new Date(),
    isDeleted: 0,
    version: 1
  };
  await axios.post('http://localhost:8085/comments', newComment);
  content.value = '';
  fetchComments();
}

/**
 * 同步加载评论数据
 * @returns {Promise<void>}
 */
async function fetchData() {
  try {
    await Promise.all([
      fetchComments()
    ]);
  } catch (error) {
    console.error('数据加载失败:', error);
  }
}

/**
 * 监听 activityId 变化并重新加载数据
 */
watch(() => props.activityId, fetchData, {immediate: true});
</script>

<style scoped>
.comment-section {
  padding: 18px 48px;
  background: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(44, 62, 80, 0.08);
  max-width: 500px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  overflow-y: visible; /* 允许内容自然扩展 */
}



.comment-list-scroll {
  overflow-y: visible; /* 关闭滚动 */
  margin-bottom: 12px;
  padding-right: 8px;
}


.comment-item {
  border-bottom: 1px solid #f0f0f0;
  padding: 8px 0;
  text-align: left;
}

.comment-user {
  font-weight: bold;
  color: #3498db;
  text-align: left;
}

.comment-content {
  margin: 4px 0;
  text-align: left;
}

.comment-date {
  font-size: 12px;
  color: #888;
  text-align: left;
}

.comment-avatar {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
  vertical-align: middle;
}

.no-comment {
  color: #aaa;
  text-align: center;
  margin: 16px 0;
}

.loading {
  color: #888;
  text-align: center;
  margin: 16px 0;
}

.comment-input-row {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 18px;
  background: #f7f8fa;
  border-radius: 12px;
  padding: 8px 16px;
  position: sticky;
  bottom: 0;
  z-index: 10;
  box-shadow: 0 -2px 8px rgba(44, 62, 80, 0.08);
  width: 100%;
  border-bottom: 1px solid #e0e6ed;
}



.input-tip {
  color: #bfc3c9;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.comment-input {
  flex: 1;
  border: none;
  background: #fff;
  font-size: 16px;
  color: #23232b;
  outline: none;
  padding: 6px 8px;
}

.primary-btn {
  background: linear-gradient(90deg, #43484e 0%, #23272b 100%);
  color: #fff;
  border: none;
  border-radius: 18px;
  font-size: 16px;
  font-weight: 500;
  padding: 8px 22px;
  cursor: pointer;
  transition: background 0.2s, box-shadow 0.2s;
}

.primary-btn:disabled {
  background: #e0e6ed;
  color: #bfc3c9;
  cursor: not-allowed;
}

.login-tip {
  color: #e74c3c;
  margin-top: 8px;
}

.close-btn {
  margin-top: 12px;
  background: #f0f2f5;
  border: none;
  border-radius: 6px;
  padding: 6px 18px;
  cursor: pointer;
  color: #3498db;
}

.close-btn:hover {
  background: #e0e6ed;
}
</style>
